package com.dongnao.network.netty_hashcat;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.util.List;
import java.util.Map;

import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;


public class ActionHandler extends SimpleChannelInboundHandler<HttpRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
        QueryStringDecoder query = new QueryStringDecoder(request.uri());
        if ("/login".equals(query.rawPath())) {
            String result = doLogin(query);
            //将结果封装到ByteBuf
            ByteBuf buf = Unpooled.wrappedBuffer(result.getBytes());
            //创建响应对象
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
            //设置响应内容长度
            HttpUtil.setContentLength(response, buf.writerIndex());
            //设置响应的contentType
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

            //将响应写给客户端
            ctx.writeAndFlush(response);
        } else {
            sendError(ctx, NOT_FOUND);
        }
    }

    //发送出错的结果
    private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
        HttpUtil.setContentLength(response, response.content().readableBytes());
        ctx.writeAndFlush(response);
    }

    private String doLogin(QueryStringDecoder query) {
        Map<String, List<String>> params = query.parameters();
        if (!params.isEmpty()) {
            List<String> names = params.get("username");
            if (names != null && names.size() > 0) {
                String userName = names.get(0);
                List<String> pwds = params.get("password");
                if (pwds != null && pwds.size() > 0) {
                    String password = pwds.get(0);
                    if ("admin".equals(userName) && "111111".equals(password)) {
                        return "登陆成功";
                    }
                }
            }
        }
        return "用户名或密码错误";
    }
}
